package main

import (
	"fmt"
	"net"
	"time"
)

/*
https://studygolang.com/static/pkgdoc/pkg/net.htm
*/

func handleConnection(conn net.Conn) {
	fmt.Printf("来自【%s】连接到服务器！\n", conn.RemoteAddr().String())
	defer conn.Close()
	// 获得客户端的消息
	for {
		byteBuff := make([]byte, 1024)
		n, err := conn.Read(byteBuff)
		if err != nil {
			fmt.Printf("客户端退出 err=%v\n", err) // 客户端退出 err=EOF
			return
		}
		recString := string(byteBuff[:n])
		fmt.Printf("客户端【%s】: %s", conn.RemoteAddr().String(), recString)
		// 发送给客户端
		now := time.Now()
		dateStr := fmt.Sprintf("hello client, server time is : %d-%d-%d %d:%d:%d \n", now.Year(),
			now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
		conn.Write([]byte(dateStr))
	}
}

func main() {

	ln, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println("监听失败，", err)
	}

	defer ln.Close()

	for {
		conn, err := ln.Accept() // 阻塞等待连接进来
		if err != nil {
			// handle error
			fmt.Println("获得连接失败，", err)
			continue
		}
		go handleConnection(conn)
	}

}
